from fastapi import APIRouter, HTTPException, Body
from typing import List
from tortoise.contrib.pydantic import pydantic_model_creator
from src.backend.models import AirportRWY as AirportRWY_model

router = APIRouter(
    prefix="/api/airportRWY",
    tags=["Airport Runways"],
)

AirportRWY_Pydantic = pydantic_model_creator(AirportRWY_model)
AirportRWY_Pydantic_In = pydantic_model_creator(AirportRWY_model, name="AirportRWYIn", exclude_readonly=True)

@router.post("/", response_model=AirportRWY_Pydantic)
async def create_airport_rwy(rwy: AirportRWY_Pydantic_In):
    rwy_obj = await AirportRWY_model.create(**rwy.dict(exclude_unset=True))
    return await AirportRWY_Pydantic.from_tortoise_orm(rwy_obj)

@router.get("/", response_model=List[AirportRWY_Pydantic])
async def get_airport_rwys():
    return await AirportRWY_Pydantic.from_queryset(AirportRWY_model.all())

@router.get("/{rwy_id}", response_model=AirportRWY_Pydantic)
async def get_airport_rwy(rwy_id: str):
    return await AirportRWY_Pydantic.from_queryset_single(AirportRWY_model.get(id=rwy_id))

@router.put("/{rwy_id}", response_model=AirportRWY_Pydantic)
async def update_airport_rwy(rwy_id: str, rwy_update: AirportRWY_Pydantic_In):
    await AirportRWY_model.filter(id=rwy_id).update(**rwy_update.dict(exclude_unset=True))
    return await AirportRWY_Pydantic.from_queryset_single(AirportRWY_model.get(id=rwy_id))

@router.delete("/{rwy_id}", response_model=dict)
async def delete_airport_rwy(rwy_id: str):
    deleted_count = await AirportRWY_model.filter(id=rwy_id).delete()
    if not deleted_count:
        raise HTTPException(status_code=404, detail="Runway not found")
    return {"message": "Runway deleted successfully"}
